package com.bcu.cn.onlineexamsystem.studentmanage.service.impl;

import com.bcu.cn.onlineexamsystem.studentmanage.service.StudentResourceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import java.util.List;

@Service
public class StudentResourceServiceImpl implements StudentResourceService {
    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Override
    public List<CourseWithQuestions> getStudentCourseQuestions(String studentId, String courseName, String type) {
        StringBuilder sql = new StringBuilder(
            "SELECT c.course_id, c.course_name, q.question_id, q.type, q.content, q.options, q.answer, q.score " +
            "FROM student_courses sc JOIN courses c ON sc.course_id = c.course_id " +
            "LEFT JOIN questions q ON c.course_id = q.course_id WHERE sc.student_id = ?"
        );
        java.util.List<Object> params = new java.util.ArrayList<>();
        params.add(studentId);
        if (courseName != null && !courseName.isEmpty()) {
            sql.append(" AND c.course_name LIKE ?");
            params.add("%" + courseName + "%");
        }
        if (type != null && !type.isEmpty()) {
            sql.append(" AND q.type = ?");
            params.add(type);
        }
        sql.append(" ORDER BY c.course_id, q.question_id");
        java.util.List<java.util.Map<String, Object>> rows = jdbcTemplate.queryForList(sql.toString(), params.toArray());
        java.util.Map<Long, CourseWithQuestions> courseMap = new java.util.LinkedHashMap<>();
        for (java.util.Map<String, Object> row : rows) {
            Long courseId = ((Number)row.get("course_id")).longValue();
            CourseWithQuestions course = courseMap.computeIfAbsent(courseId, id -> {
                CourseWithQuestions c = new CourseWithQuestions();
                c.courseId = id;
                c.courseName = (String) row.get("course_name");
                c.questions = new java.util.ArrayList<>();
                return c;
            });
            if (row.get("question_id") != null) {
                QuestionInfo q = new QuestionInfo();
                q.questionId = row.get("question_id") == null ? null : ((Number)row.get("question_id")).longValue();
                q.type = (String) row.get("type");
                q.content = (String) row.get("content");
                q.options = row.get("options") == null ? null : row.get("options").toString();
                q.answer = (String) row.get("answer");
                q.score = row.get("score") == null ? null : row.get("score").toString();
                course.questions.add(q);
            }
        }
        return new java.util.ArrayList<>(courseMap.values());
    }

    @Override
    public List<CourseWithQuestions> getStudentCourseQuestions(String studentId) {
        return getStudentCourseQuestions(studentId, null, null);
    }
} 